﻿using Inovout.Cloud.Storage.Web.Models;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;

namespace Inovout.Cloud.Storage.Web.Controllers
{
    public class UploadController : ObjectsController
    {
        [Route("v1/upload/")]
        public Task<ObjectInfo> Put(string uploadType, string upload_id)
        {
            if (uploadType.Equals("resumable"))
            {
                return ResumableUpload(upload_id);
            }
            throw new System.NotSupportedException("只支持resumable方式上传");
        }
        [HttpPut]
        public async Task<ObjectInfo> ResumableUpload(string upload_id)
        {
            using (Stream stream = await this.Request.Content.ReadAsStreamAsync().ConfigureAwait(false))
            {
                ContentRangeHeaderValue range = this.Request.Content.Headers.ContentRange;
                Stream fileStream = null;
                if (range.From.Value == 0)
                {
                    fileStream = new FileStream(Path.Combine(GetUploadFolderName(), upload_id.ToString()),
                         System.IO.FileMode.Create, System.IO.FileAccess.Write);
                }
                else
                {
                    fileStream = new FileStream(Path.Combine(GetUploadFolderName(), upload_id.ToString()),
                         System.IO.FileMode.Append, System.IO.FileAccess.Write);
                }
                System.IO.MemoryStream ms = new MemoryStream();
                if (range.HasRange)
                {
                    if (range.From.Value == 0)
                    {
                        stream.CopyTo(fileStream);
                    }
                    else
                    {
                        byte[] buffer = new byte[stream.Length];
                        fileStream.Write(buffer, (int)range.From.Value, buffer.Length);
                    }
                }
                fileStream.Close();
                ObjectInfo storageObject = null;
                if (range.To.Value.Equals(range.Length - 1))
                {
                    using (fileStream = new FileStream(Path.Combine(GetUploadFolderName(), upload_id.ToString()),
                          FileMode.Open, System.IO.FileAccess.Read))
                    {
                        storageObject = await Upload(upload_id, fileStream).ConfigureAwait(false);
                    }

                }
                return storageObject;
            }

        }

        //[HttpGet]
        //public HttpResponseMessage GetUploadPath(string upload_id)
        //{
        //    return Content(fileService.FindByKey(upload_id).Path);
        //}


    }
}